
package com.hlkj.pay.app.merchant.ext.impl.guogpay.ext;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.fasterxml.jackson.core.type.TypeReference;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelPayOrderQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelRefundPayOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.constant.GuogPayConstant;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.GuogPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.GuogpayAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.req.OrderQueryReq;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.req.OrderRefundReq;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.HttpResponse;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.OrderQueryRsp;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.OrderRefundQueryRsp;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.dto.rsp.OrderRefundRsp;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.utils.GuogPaySignUtil;
import com.hlkj.pay.app.merchant.ext.impl.guogpay.utils.HttpUtils;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.order.RefundOrderDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.MerchantUtils;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

/**
 * 国广支付 正扫 反扫 通用处理
 * 
 * @author HlpayTeam
 * @date 2024/10/11 16:22
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class GuogPaySceneCommonPayOrder {

    /**
     * 国广支付查询支付订单
     *
     * @param channelPayOrderQueryContext
     */
    public void commonQueryChannelPayOrder(ChannelPayOrderQueryContext channelPayOrderQueryContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelPayOrderQueryContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GuogPayConfig payConfig = getPayConfig(channelConfig, channelPayOrderQueryContext.getMerchantAppChannelDO());
        PayOrderDO payOrderDO = channelPayOrderQueryContext.getPayOrderDO();
        try {
            OrderQueryReq orderQueryReq = new OrderQueryReq();
            orderQueryReq.setMerchantNo(payConfig.getMerchantNo());
            orderQueryReq.setOutTradeNo(payOrderDO.getPayOrderNo());
            orderQueryReq.setRequestId(SequenceTools.getReqSeqId32());
            orderQueryReq.setTimestamp(getCurrenttime());
            orderQueryReq.setSign(GuogPaySignUtil.sign(orderQueryReq, payConfig.getMd5Key()));

            log.info("国广支付订单查询req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelPayOrderQueryContext.isTest()) + GuogPayConstant.TRADE_QUERY;
            String response = HttpUtils.get(url, JsonUtils.parseObj(orderQueryReq));
            log.info("国广支付订单查询返回参数:{}", response);

            // 响应报文验签
            HttpResponse<OrderQueryRsp> rspBody = JsonUtils.parseObject(response, new TypeReference<>() {
            });
            if ("0000".equals(rspBody.getCode())) {
                OrderQueryRsp queryRsp = rspBody.getData();
                PayOrderDO updartePayOrderDO = new PayOrderDO();
                switch (queryRsp.getStatus()) {
                    case "SUCCESS":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.SUCCESS.getCode());
                        updartePayOrderDO.setSuccessTime(GuogPaySignUtil.converDate(queryRsp.getPayTime()));
                        break;
                    case "CLOSE":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.CLOSE.getCode());
                        break;
                    case "PROCESSING":
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.PAYING.getCode());
                        break;
                    default:
                        updartePayOrderDO.setState(PayOrderEnums.PAY_ORDER_STATUS.FAIL.getCode());
                }

                updartePayOrderDO.setInsOrderNo(queryRsp.getPlatformTxNo());
                channelPayOrderQueryContext.setUpdartePayOrderDO(updartePayOrderDO);
            }
            else {
                String respDesc = rspBody.getMessage();
                channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelPayOrderQueryContext.setRemark(respDesc);
                }
                else {
                    channelPayOrderQueryContext.setRemark("国广支付提交支付订单查询返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("国广支付查询支付订单请求失败 message:{}", e.getMessage(), e);
            channelPayOrderQueryContext.setRemark("国广支付查询支付订单请求失败,失败信息" + e.getMessage());
            channelPayOrderQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 国广支付订单退款
     *
     * @param channelRefundPayOrderContext
     */
    public void commonRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GuogPayConfig payConfig = getPayConfig(channelConfig, channelRefundPayOrderContext.getMerchantAppChannelDO());

        PayOrderDO payOrderDO = channelRefundPayOrderContext.getPayOrderDO();
        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        try {

            OrderRefundReq orderQueryReq = new OrderRefundReq();
            orderQueryReq.setOutRefundNo(refundOrderDO.getRefundOrderNo());
            orderQueryReq.setMerchantNo(payConfig.getMerchantNo());
            orderQueryReq.setRequestId(refundOrderDO.getRefundOrderNo());
            orderQueryReq.setOutTradeNo(payOrderDO.getPayOrderNo());
            orderQueryReq.setAmount(MerchantUtils.YuanToFen(refundOrderDO.getRefundAmount()));
            orderQueryReq.setRefundReason(refundOrderDO.getRefundReason());
            orderQueryReq.setTimestamp(getCurrenttime());
            orderQueryReq.setSign(GuogPaySignUtil.sign(orderQueryReq, payConfig.getMd5Key()));

            log.info("国广支付订单退款req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelRefundPayOrderContext.isTest()) + GuogPayConstant.REFUND_ORDER;
            String response = HttpUtils.post(url, orderQueryReq);
            log.info("国广支付订单退款返回参数:{}", response);

            // 响应报文验签
            HttpResponse<OrderRefundRsp> ordeRsp = JsonUtils.parseObject(response, new TypeReference<>() {
            });
            //2004退款中，0000退款成功
            if ("2004".equals(ordeRsp.getCode()) || "0000".equals(ordeRsp.getCode())) {
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());
                updateRefundOrderDO.setSuccessTime(System.currentTimeMillis());
                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = ordeRsp.getMessage();
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("国广支付提交退款订单返回错误信息为空,错误码为:" + ordeRsp.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("国广支付提交退款订单请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("国广支付提交退款订单请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 国广支付订单退款状态查询
     *
     * @param channelRefundPayOrderContext
     */
    public void commonQueryRefundChannelPayOrder(ChannelRefundPayOrderContext channelRefundPayOrderContext) {
        ProviderChannelConfigDO providerChannelConfigDO = channelRefundPayOrderContext.getProviderChannelConfigDO();
        String channelConfig = providerChannelConfigDO.getParamsConfig();
        // 配置转换
        GuogPayConfig payConfig = getPayConfig(channelConfig, channelRefundPayOrderContext.getMerchantAppChannelDO());

        RefundOrderDO refundOrderDO = channelRefundPayOrderContext.getRefundOrderDO();
        try {
            OrderQueryReq orderQueryReq = new OrderQueryReq();
            orderQueryReq.setMerchantNo(payConfig.getMerchantNo());
            orderQueryReq.setOutTradeNo(refundOrderDO.getPayOrderNo());
            orderQueryReq.setRequestId(SequenceTools.getReqSeqId32());
            orderQueryReq.setTimestamp(getCurrenttime());
            orderQueryReq.setSign(GuogPaySignUtil.sign(orderQueryReq, payConfig.getMd5Key()));

            log.info("国广支付订单退款查询req参数:{}", JsonUtils.toJsonString(orderQueryReq));
            String url = domain(channelRefundPayOrderContext.isTest()) + GuogPayConstant.REFUND_QUERY;
            String response = HttpUtils.get(url, JsonUtils.parseObj(orderQueryReq));
            log.info("国广支付订单退款查询返回参数:{}", response);

            HttpResponse<OrderRefundQueryRsp> rspBody = JsonUtils.parseObject(response, new TypeReference<>() {
            });
            if ("0000".equals(rspBody.getCode())) {
                OrderRefundQueryRsp refundRsp = rspBody.getData();
                RefundOrderDO updateRefundOrderDO = new RefundOrderDO();
                switch (refundRsp.getStatus()) {
                    case "SUCCESS":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUND.getCode());
                        updateRefundOrderDO.setSuccessTime(System.currentTimeMillis());
                        break;
                    case "FAIL":
                    case "CLOSE":
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.FAIL.getCode());
                        break;
                    default:
                        updateRefundOrderDO.setRefundStatus(PayOrderEnums.REFUND_STATUS.REFUNDING.getCode());
                        break;
                }
                channelRefundPayOrderContext.setUpdateRefundOrderDO(updateRefundOrderDO);
            }
            else {
                String respDesc = rspBody.getMessage();
                channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
                if (StringUtils.hasText(respDesc)) {
                    channelRefundPayOrderContext.setRemark(respDesc);
                }
                else {
                    channelRefundPayOrderContext.setRemark("国广支付提交退款订单返回错误信息为空,错误码为:" + rspBody.getCode());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("国广支付退款订单查询请求失败 message:{}", e.getMessage(), e);
            channelRefundPayOrderContext.setRemark("国广支付退款订单查询请求失败,失败信息" + e.getMessage());
            channelRefundPayOrderContext.setProcessStatus(Boolean.FALSE);
        }
    }

    public GuogpayAppChannelParams appChannelParams(MerchantAppChannelDO merchantAppChannelDO) {
        return JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), GuogpayAppChannelParams.class);
    }

    public String domain(boolean test) {
        return GuogPayConstant.PAY_ORDER_DOMAIN_PROD;
    }

    public Integer expireMinute(Long time) {
        if (time == null) {
            return 30;
        }
        return (int) (time - System.currentTimeMillis()) / 1000 / 60;
    }

    //转换是如果商户有单独配置 取商户配置
    public GuogPayConfig getPayConfig(String channelConfig, MerchantAppChannelDO merchantAppChannelDO) {
        // 配置转换
        GuogPayConfig payConfig = JsonUtils.parseObject(channelConfig, GuogPayConfig.class);

        GuogpayAppChannelParams dffpayAppChannelParams = appChannelParams(merchantAppChannelDO);

        if (StringUtils.hasText(dffpayAppChannelParams.getMd5Key()))
            payConfig.setMd5Key(dffpayAppChannelParams.getMd5Key());

        if (StringUtils.hasText(dffpayAppChannelParams.getMerchantNo()))
            payConfig.setMerchantNo(dffpayAppChannelParams.getMerchantNo());
        return payConfig;
    }

    public long getCurrenttime() {
        return (System.currentTimeMillis() / 1000);
    }
}
